package com.shuke.medical.insure.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/***
 * @title MedicalInsureInOutUtil
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/23 9:25
 **/
@Slf4j
public class ChsInOutUtil {

    public static final String DEFAULT_INPUT_KEY = "data";
    public static final String DEFAULT_OUTPUT_KEY = "result";

    public static JSONObject toInPut(Object obj) {
        return toInPutByKey(DEFAULT_INPUT_KEY, obj);
    }

    public static JSONObject toInPutByKey(String key, Object obj) {
        JSONObject input = new JSONObject();
        input.put(key, obj);
        return input;
    }

    public static <T> T toOutPut(String outPut, Class<T> clz) {
        return toOutPutByKey(outPut, DEFAULT_OUTPUT_KEY, clz);
    }

    public static <T> T toOutPutByKey(String outPut, String key, Class<T> clz) {
        HashMap outPutMap = JSONObject.parseObject(outPut, HashMap.class);

        Assert.isTrue(outPutMap.containsKey(key),
                "根据key获取数据出参失败，key: [{}]不存在", key);

        Object obj = outPutMap.get(key);
        T t;
        try {
            t = clz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("method MedicalInsureInOutUtil.toOutPutSingle() arg 'Class<T> clz' newInstance failed ! please check clz has constructor...");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("method MedicalInsureInOutUtil.toOutPutSingle() arg 'Class<T> clz' newInstance failed ! please check clz has constructor...");
        }
        BeanUtil.copyProperties(obj, t);
        return t;
    }
}
